package com.cn.algorithm.two.line.test;

import java.util.Arrays;

public class BucketSortJ {
    public static void main(String[] args) {
        int[] arr = {9, 7, 4, 2, 5, 3, 8};
        sort(arr, 4);
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(int[] arr, int bucketSize) {
        if (arr == null || arr.length <= 1 || bucketSize < 1) {
            return;
        }
        int max = arr[0];
        int min = max;
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            } else if (arr[i] < min) {
                min = arr[i];
            }
        }
        int[][] tmp = new int[bucketSize][max + 1];
        for (int i = 0; i < arr.length; i++) {
            tmp[(arr[i] - min) * (bucketSize - 1) / (max - min)][arr[i]]++;
        }
        int index = 0;
        for (int[] array : tmp) {
            for (int i = min; i < array.length; i++) {
                if (array[i] > 0) {
                    arr[index++] = i;
                }
            }
        }
    }
}
